package com.analysis.server.controller;

import com.analysis.server.mapper.LogTemplateMapper;
import com.analysis.server.model.LogTemplate;
import com.analysis.server.model.SlowSqlResult;
import com.analysis.server.service.LogAnalysisService;
import com.analysis.server.service.LogAnalysisPerformanceMonitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日志分析控制器
 * 提供文件上传和慢SQL分析接口
 */
@RestController
@RequestMapping("/api/template")
public class LogAnalysisController {
    @Autowired
    private LogTemplateMapper logTemplateMapper;
    @Autowired
    private LogAnalysisService logAnalysisService;
    
    /**
     * 上传日志文件并分析慢SQL
     * @param file 上传的日志文件
     * @param templateId 模板ID（可选）
     * @return 分析结果
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadAndAnalyze(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "templateId", required = false) Long templateId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择要上传的日志文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查文件大小（100MB限制）
            if (file.getSize() > 100 * 1024 * 1024) {
                response.put("success", false);
                response.put("message", "文件大小不能超过100MB");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".log") && !fileName.endsWith(".txt"))) {
                response.put("success", false);
                response.put("message", "请上传.log或.txt格式的日志文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 分析日志文件
            List<SlowSqlResult> slowSqlResults;
            if (templateId != null) {
                // 使用模板分析
                slowSqlResults = logAnalysisService.analyzeLogFileWithTemplate(file, templateId);
            } else {
                // 使用默认分析
                slowSqlResults = logAnalysisService.analyzeLogFile(file);
            }
            
            response.put("success", true);
            response.put("message", "日志分析完成");
            response.put("data", slowSqlResults);
            response.put("totalCount", slowSqlResults.size());
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "文件读取失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "分析过程中发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("message", "日志分析服务运行正常");
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取性能监控数据
     * @return 性能监控快照
     */
    @GetMapping("/performance")
    public ResponseEntity<Map<String, Object>> getPerformanceData() {
        Map<String, Object> response = new HashMap<>();
        try {
            LogAnalysisPerformanceMonitor.PerformanceSnapshot snapshot = 
                logAnalysisService.getPerformanceSnapshot();
            
            response.put("success", true);
            response.put("data", snapshot);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取性能数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 测试性能监控器注入
     * @return 测试结果
     */
    @GetMapping("/test-monitor")
    public ResponseEntity<Map<String, Object>> testMonitor() {
        Map<String, Object> response = new HashMap<>();
        try {
            // 直接测试性能监控器
            LogAnalysisPerformanceMonitor.PerformanceSnapshot snapshot = 
                logAnalysisService.getPerformanceSnapshot();
            
            response.put("success", true);
            response.put("message", "性能监控器注入正常");
            response.put("data", snapshot);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "性能监控器注入失败: " + e.getMessage());
            response.put("exception", e.getClass().getSimpleName());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 手动重置性能监控指标
     */
    @PostMapping("/performance/reset")
    public ResponseEntity<Map<String, Object>> resetPerformanceMetrics() {
        Map<String, Object> response = new HashMap<>();
        try {
            logAnalysisService.resetPerformanceMetrics();
            response.put("success", true);
            response.put("message", "性能指标已重置");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "重置失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }


    /**
     * 上传日志文件并分析慢SQL（支持模板id）
     */
    @PostMapping("/uploadWithTemplate")
    public ResponseEntity<Map<String, Object>> uploadAndAnalyzeWithTemplate(
            @RequestParam("file") MultipartFile file,
            @RequestParam("templateId") Long templateId) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择要上传的日志文件");
                return ResponseEntity.badRequest().body(response);
            }
            if (file.getSize() > 100 * 1024 * 1024) {
                response.put("success", false);
                response.put("message", "文件大小不能超过100MB");
                return ResponseEntity.badRequest().body(response);
            }
            List<SlowSqlResult> slowSqlResults = logAnalysisService.analyzeLogFileWithTemplate(file, templateId);
            response.put("success", true);
            response.put("message", "日志分析完成");
            response.put("data", slowSqlResults);
            response.put("totalCount", slowSqlResults.size());
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "文件读取失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "分析过程中发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @GetMapping
    public List<LogTemplate> list() {
        return logTemplateMapper.findAll();
    }

    @PostMapping
    public ResponseEntity<?> add(@RequestBody LogTemplate template) {
        if (logTemplateMapper.findByName(template.getName()) != null) {
            return ResponseEntity.badRequest().body("模板名称已存在");
        }
        logTemplateMapper.insert(template);
        return ResponseEntity.ok(template);
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> update(@PathVariable Long id, @RequestBody LogTemplate template) {
        LogTemplate old = logTemplateMapper.findById(id);
        if (old == null) {
            return ResponseEntity.notFound().build();
        }
        template.setId(id);
        logTemplateMapper.update(template);
        return ResponseEntity.ok(template);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        if (logTemplateMapper.findById(id) == null) {
            return ResponseEntity.notFound().build();
        }
        logTemplateMapper.delete(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 测试模板正则表达式
     */
    @PostMapping("/test")
    public ResponseEntity<Map<String, Object>> testTemplate(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();

        try {
            Long templateId = Long.valueOf(request.get("templateId").toString());
            String logText = request.get("logText").toString();

            LogTemplate template = logTemplateMapper.findById(templateId);
            if (template == null) {
                response.put("success", false);
                response.put("message", "模板不存在");
                return ResponseEntity.badRequest().body(response);
            }

            List<Map<String, Object>> results = logAnalysisService.testTemplateRegex(template, logText);

            response.put("success", true);
            response.put("data", results);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "测试失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 生成正则表达式
     */
    @PostMapping("/generateRegex")
    public ResponseEntity<Map<String, Object>> generateRegex(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();

        try {
            String template = request.get("template").toString();
            String regex = LogAnalysisService.templateToRegex(template);

            response.put("success", true);
            response.put("regex", regex);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "生成正则失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }


}